package com.innovation.sys.common.utils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import com.innovation.sys.pojo.SSysPermissions;

public class LangUtils {

	public static String getModule(String uri) {
		List<Integer> list = new ArrayList<>();
		for (int i = 0; i < uri.length(); i++) {
			char c = uri.charAt(i);
			if (c == '/') {
				list.add(i);
			}
		}
		int index = list.get(list.size() - 2);
		int subindex = list.get(list.size() - 1);
		return uri.substring(index + 1, subindex);
	}

	public static void main(String[] args) {
		getModule("/currency/api/admin/sys/log/listOfLog.do");
	}

	public static boolean isEmpty(Object obj) {
		if (obj == null) {
			return true;
		}
		if (obj instanceof String) {
			return ((String) obj).trim().equals("");
		}
		if (obj instanceof Object[]) {
			return ((Object[]) obj).length == 0;
		}
		if (obj instanceof Collection) {
			return ((Collection<?>) obj).isEmpty();
		}
		return false;
	}

	public static boolean isNotEmpty(Object obj) {
		return !LangUtils.isEmpty(obj);
	}

	@SuppressWarnings("unchecked")
	public static <T> List<T> removeNull(List<? extends T> oldList) {
		oldList.removeAll(Collections.singleton(null));
		return (List<T>) oldList;
	}

	public static String trimCn(String str) {
		if (str == null)
			return null;
		str = str.trim();
		if (str.length() == 0)
			return str;
		int st = 0;
		int len = str.length();
		while ((st < len) && str.charAt(st) == '　')
			st++;
		while ((st < len) && str.charAt(len - 1) == '　')
			len--;
		if (st > 0 || len < str.length())
			str = str.substring(st, len);
		return str.trim();
	}

	public static boolean contains(Object[] array, Object item) {
		for (Object obj : array) {
			if (obj.equals(item)) {
				return true;
			}
		}
		return false;
	}

	public static String makeSqlLike(String key) {
		return LangUtils.isNotEmpty(key) ? "%" + key.trim().replaceAll("\\s", "%") + "%" : null;
	}

	public static String isoToUtf8(String str) {
		if (str == null)
			return null;
		try {
			return new String(str.getBytes("iso-8859-1"), "utf-8");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String formatDate(Date date) {
		if (date == null)
			return null;
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
	}

	public static String formatDate(Date date, String formatStyle) {
		if (date == null || isEmpty(formatStyle))
			return null;
		return new SimpleDateFormat(formatStyle).format(date);
	}

	public static Date parseDate(String str) {
		if (str == null)
			return null;
		try {
			String f = (str.length() == 10 ? "yyyy-MM-dd" : "yyyy-MM-dd HH:mm:ss");
			return new SimpleDateFormat(f).parse(str);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static boolean checkDate(String dateStr, String format) {
		SimpleDateFormat df = new SimpleDateFormat(format);
		Date date = null;
		try {
			date = df.parse(dateStr);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		String dateStr2 = df.format(date);
		return dateStr.equals(dateStr2);
	}

	public static Long parseLong(String str) {
		if (str == null)
			return null;
		try {
			return Long.parseLong(str);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static Integer parseInteger(Object strObj) {
		return LangUtils.parseInteger(strObj.toString());
	}

	public static Integer parseInteger(String str) {
		if (str == null)
			return null;
		try {
			return Integer.parseInt(str);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static Float parseFloat(String str) {
		if (str == null)
			return null;
		try {
			return Float.parseFloat(str);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static Double parseDouble(String str) {
		if (str == null)
			return null;
		try {
			return Double.parseDouble(str);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String getString(Object obj) {
		if (isNotEmpty(obj))
			return obj.toString();
		return null;
	}

	public static Integer[] convertString2Int(String[] ids) {
		Integer[] nameids = new Integer[ids.length];
		for (int i = 0; i < ids.length; i++) {
			if (isNotEmpty(ids[i])) {
				nameids[i] = Integer.parseInt(ids[i]);
			}
		}
		return nameids;
	}

	public static String escapeHtml(String html) {
		if (html == null)
			return null;
		return html.replaceAll("<", "&lt;");
	}

	public static String makeSqlOrderBy(String sortName, String sortOrder) {
		if (isNotEmpty(sortName) && isNotEmpty(sortOrder)) {
			return "  order by " + sortName.trim() + "  " + sortOrder.trim();
		} else {
			return null;
		}
	}

	public static Double decimalFormat(Double num) {
		DecimalFormat df = new DecimalFormat("#.00");
		return parseDouble(df.format(num));
	}

	public static String numberFormat(Double num) {
		NumberFormat nf = NumberFormat.getInstance();
		nf.setGroupingUsed(false);
		return nf.format(num);
	}

	public static boolean isNumeric(String str) {
		for (int i = str.length(); --i >= 0;) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	public static boolean isNumeric_gz(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}

	public static boolean isNumeric_asci(String str) {
		for (int i = str.length(); --i >= 0;) {
			int chr = str.charAt(i);
			if (chr < 48 || chr > 57)
				return false;
		}
		return true;
	}

	public static int getRandom(int length) {
		int num = 1;
		double random = Math.random();
		if (random < 0.1) {
			random = random + 0.1;
		}
		for (int i = 0; i < length; i++) {
			num = num * 10;
		}
		return (int) ((random * num));

	}

	public static String decode(String value) {
		String decode_value = "";
		try {
			decode_value = URLDecoder.decode(value, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		return decode_value;
	}

	public static String incode(String value) {
		String encode_value = "";
		try {
			encode_value = URLEncoder.encode(value, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		return encode_value;
	}

	public static String digitUppercase(String num) throws Exception {
		String digit[] = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
		/**
		 * 仟 佰 拾 ' ' ' ' $4 $3 $2 $1 万 $8 $7 $6 $5 亿 $12 $11 $10 $9
		 */
		String unit1[] = { "", "拾", "佰", "仟" };// 把钱数分成段,每四个一段,实际上得到的是一个二维数组
		String unit2[] = { "元", "万", "亿", "万亿" }; // 把钱数分成段,每四个一段,实际上得到的是一个二维数组
		BigDecimal bigDecimal = new BigDecimal(num);
		bigDecimal = bigDecimal.multiply(new BigDecimal(100));
		String strVal = String.valueOf(bigDecimal.toBigInteger());
		String head = strVal.substring(0, strVal.length() - 2); // 整数部分
		String end = strVal.substring(strVal.length() - 2); // 小数部分
		String endMoney = "";
		String headMoney = "";
		if ("00".equals(end)) {
			endMoney = "整";
		} else {
			if (!end.substring(0, 1).equals("0")) {
				endMoney += digit[Integer.valueOf(end.substring(0, 1))] + "角";
			} else if (end.substring(0, 1).equals("0") && !end.substring(1, 2).equals("0")) {
				endMoney += "零";
			}
			if (!end.substring(1, 2).equals("0")) {
				endMoney += digit[Integer.valueOf(end.substring(1, 2))] + "分";
			}
		}
		char[] chars = head.toCharArray();
		Map<String, Boolean> map = new HashMap<String, Boolean>();// 段位置是否已出现zero
		boolean zeroKeepFlag = false;// 0连续出现标志
		int vidxtemp = 0;
		for (int i = 0; i < chars.length; i++) {
			int idx = (chars.length - 1 - i) % 4;// 段内位置 unit1
			int vidx = (chars.length - 1 - i) / 4;// 段位置 unit2
			String s = digit[Integer.valueOf(String.valueOf(chars[i]))];
			if (!"零".equals(s)) {
				headMoney += s + unit1[idx] + unit2[vidx];
				zeroKeepFlag = false;
			} else if (i == chars.length - 1 || map.get("zero" + vidx) != null) {
				headMoney += "";
			} else {
				headMoney += s;
				zeroKeepFlag = true;
				map.put("zero" + vidx, true);// 该段位已经出现0；
			}
			if (vidxtemp != vidx || i == chars.length - 1) {
				headMoney = headMoney.replaceAll(unit2[vidx], "");
				headMoney += unit2[vidx];
			}
			if (zeroKeepFlag && (chars.length - 1 - i) % 4 == 0) {
				headMoney = headMoney.replaceAll("零", "");
			}
		}
		return headMoney + endMoney;
	}

	public static String decimalToPercent(BigDecimal num) {
		DecimalFormat df = new DecimalFormat("0.00%");
		return num == null ? null : df.format(num);
	}

	public static boolean isIntegerValue(BigDecimal decimalVal) {
		return decimalVal.scale() <= 0 || decimalVal.stripTrailingZeros().scale() <= 0;
	}

	public static boolean equals(Object obj, Object obj1) {
		boolean flag = false;
		if (obj instanceof SSysPermissions && obj1 instanceof SSysPermissions) {
			SSysPermissions permission = (SSysPermissions) obj;
			SSysPermissions anotherPermission = (SSysPermissions) obj1;
			if (permission.getPerId() == anotherPermission.getPerId()
					&& permission.getMenu().equals(anotherPermission.getMenu())
					&& permission.getPermission().equals(anotherPermission.getPermission())) {
				flag = true;
			}
		}
		return flag;
	}

}
